package com.damai.action.json;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.JsonUtil;
import com.citywithincity.utils.RequestUtil;
import com.damai.error.ApiError;

class FileGetJson implements IGetJson  {
	
	/**
	 * 文件头格式为
	 * name[i].name[i]:1024
	 * 或者
	 * name[i]:1024
	 * 
	 * 需要区分是array中带File还是Array中带map
	 */
	
	private static final Log logger = LogFactory.getLog(FileGetJson.class);
	
	
	private static final Pattern pattern = Pattern.compile("([^\\[]+)\\[([0-9]+)\\]");
	protected Map<String, Object> read(byte[] bytes,HttpServletRequest request) throws IOException{
		return  JsonUtil.read(bytes);
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Map<String, Object> getJson(HttpServletRequest request) throws IOException {
		InputStream inputStream = null;
		try{
			inputStream = request.getInputStream();
			int contentLength = request.getContentLength();
			if(contentLength<=0){
				String totalLen = request.getHeader("totalLength");
				if(totalLen==null){
					logger.info("Header:"+RequestUtil.getHeaders(request));
					throw new ApiError("Header must contains : totalLength");
				}
				contentLength = Integer.parseInt(totalLen);
			}
			String strLen = request.getHeader("fileLength");
			int fileLength =0;
			if(strLen!=null){
				 fileLength = Integer.parseInt(strLen);
			}
			int jsonLen = contentLength - fileLength;
			byte[] bytes = new byte[jsonLen];
			IoUtil.read(bytes,inputStream);
			
			Map<String, Object> params = read(bytes,request);
			if(fileLength ==0 ){
				return params;
			}
			String attach = request.getHeader("attach");
			String[] files = attach.split(",");
			
			for (String file : files) {
				//对于其中一个文件
				String[] parts = file.split(":");
				String path = parts[0];
				int thisFileLength = Integer.parseInt(parts[1]);
				String[] names = path.split("\\.");
				
				Map<String, Object> context = params;
				int last = names.length-1;
				int index = 0 ; 
				for (String name : names) {
					Matcher matcher = pattern.matcher(name);
					boolean matches = matcher.matches();
					if (matches) {
						name = matcher.group(1);
						int n = Integer.parseInt(matcher.group(2));
						List list = (List) context.get(name);
						Object value = list.get(n);
						if(value==null){
							//没有下一个了,直接这个就是文件
							list.set(n,  read(inputStream, thisFileLength));
							break;
						}
						context = (Map<String, Object>) list.get(n);
					}
					//如果是最后一个
					if(index==last){
						//文件或者二进制,这里读取
						//这里统一按照二进制处理
						context.put(name, read(inputStream, thisFileLength));
						break;
					}
					
					if(!matches){
						context =  (Map<String, Object>) context.get(name);
					}
					++index;
				}
			}
			return params;
		}finally{
			IoUtil.close(inputStream);
		}
	}
	
	private byte[] read(InputStream inputStream,int thisFileLength) throws IOException{
		byte[] fileContent = new byte[thisFileLength];
		IoUtil.read(fileContent, inputStream);
		return fileContent;
	}

}
